﻿using System;
using System.Collections.Generic;
using umbraco.cms.businesslogic.media;
using umbraco.presentation.webservices;

namespace ProlificNotion.Umbraco.MediaSorter
{
    public partial class SortMedia : System.Web.UI.Page
    {
        /// <summary>
        /// Handles the Click event of the sortButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void sortButton_Click(object sender, EventArgs e)
        {
            PerformSort(int.Parse(umbraco.helper.Request("ID")));

            //- Add javascript to reload tree node and close modal
            ClientScript.RegisterClientScriptBlock(this.GetType(), "reloadTree", "top.reloadCurrentNode();", true);
            successNotice.Visible = true;
            sortPlaceHolder.Visible = false;
        }

        private void PerformSort(int ParentNodeId)
        {
            Media m = new Media(ParentNodeId);
            nodeSorter ns = new nodeSorter();
            string sortOrder = String.Empty;
            List<Media> nodes = new List<Media>();

            //- If the sort is requested on the root media node
            if (ParentNodeId == -1)
            {
                //- Get the root nodes
                Media[] roots = Media.GetRootMedias();
                nodes = new List<Media>(roots);
            }
            else
            {
                nodes = new List<Media>(m.Children);
            }

            nodes.Sort(new MediaNameCompare());

            //- Add folders to the sort list
            foreach (Media item in nodes)
            {
                if (item.ContentType.Alias.Equals("Folder"))
                {   
                    //- Recursively sort child folders if option is selected
                    if(recurseCheckBox.Checked) PerformSort(item.Id);
                    sortOrder += item.Id + ",";
                }
            }

            //- Add other files to the sort list
            foreach (Media item in nodes)
            {
                if (!item.ContentType.Alias.Equals("Folder"))
                {
                    sortOrder += item.Id + ",";
                }
            }

            //- Only attempt the sort if there are nodes to sort or a 
            //- System.ArgumentOutOfRangeException exception will be thrown
            if (sortOrder.Length > 0)
            {
                //- Call the webservice nodeSorter to update the sort order
                ns.UpdateSortOrder(m.Id, sortOrder.Substring(0, sortOrder.Length - 1));
            }
        }
    }

    public class MediaNameCompare : IComparer<Media>
    {
        /// <summary>
        /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
        /// </summary>
        /// <param name="x">The first object to compare.</param>
        /// <param name="y">The second object to compare.</param>
        /// <returns>
        /// Value Condition Less than zero<paramref name="x"/> is less than <paramref name="y"/>.Zero<paramref name="x"/> equals <paramref name="y"/>.Greater than zero<paramref name="x"/> is greater than <paramref name="y"/>.
        /// </returns>
        public int Compare(Media x, Media y)
        {
            int returnValue = 1;

            returnValue = x.Text.CompareTo(y.Text);

            return returnValue;
        }
    }
}
